﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using Common.Library;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using Common.Utilities;

namespace OnlineVideos.Views
{
    public partial class EditStory : PhoneApplicationPage
    {
        ObservableCollection<Stories> story = new ObservableCollection<Stories>();
        public EditStory()
        {
            InitializeComponent();
            Loaded += EditStory_Loaded;
        }
        
        void EditStory_Loaded(object sender, RoutedEventArgs e)
        {
            PageHelper.RemoveEntryFromBackStack("EditStory");
            loadstory();
        }
        public void loadstory()
        {
            int showid = AppSettings.ShowUniqueID;

            story = new ObservableCollection<Stories>(Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).OrderBy(j => j.paraId).ToListAsync().Result);
            if (story.Count() == 0)
                grd2.Visibility = Visibility.Visible;
            else
            {
                grd2.Visibility = Visibility.Collapsed;
                lbxeditstory.ItemsSource = story;
            }
        }
        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
        }
        private void edit_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.editstory = true;
            Constants.ParaId = (int)(sender as Image).Tag;
            NavigationService.Navigate(new Uri("/Views/Story.xaml?PageName=EditStory.xaml", UriKind.Relative));
        }

        private void delete_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            int showid = AppSettings.ShowUniqueID;
            int paraid = (int)(sender as Image).Tag;
           
            Stories s =Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId == paraid).FirstOrDefaultAsync().Result;
            string image = s.Image;
            Constants.connection.DeleteAsync(s);
       
            story.Remove(story.Where(i => i.ShowID == showid && i.paraId == paraid).FirstOrDefault());
            if (!string.IsNullOrEmpty(image))
            {
                if (Task.Run(async()=>await Storage.FileExists("Images/storyImages/" + showid + "/" + image)).Result)
                {
                    Storage.DeleteFile("Images/storyImages/" + showid + "/" + image);
                }
            }
        }
    }
}